import { ContactType } from '@/services/contacts'
import useUIMemory from './memory'

/**
 * 维护当前要显示的联系人类型
 */
const supportTypes = [ContactType.external, ContactType.group, ContactType.internal] as const
type SupportType = (typeof supportTypes)[number]

export function useContactType() {
  const [_type, _setType] = useUIMemory('contact-type', ContactType.external)

  // 保证即使 storage 里有异常值，也能返回合法的 type（之前有 bug，可能存下了错误的 type）
  const type = useMemo(
    () =>
      supportTypes.find(v => v === _type) !== undefined
        ? (_type as SupportType)
        : ContactType.external,
    [_type],
  )

  // 保证记录正确的 type
  const setType = useCallback(
    (type: ContactType) => {
      _setType(type === ContactType.notice ? ContactType.internal : type)
    },
    [_setType],
  )

  return [type, setType] as const
}
